﻿using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace QrCodeForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        const string _wechat_QCODE_detector_prototxt_path = "models/wechat_qrcode/detect.prototxt";
        const string _wechat_QCODE_detector_caffe_model_path = "models/wechat_qrcode/detect.caffemodel";
        const string _wechat_QCODE_super_resolution_prototxt_path = "models/wechat_qrcode/sr.prototxt";
        const string _wechat_QCODE_super_resolution_caffe_model_path = "models/wechat_qrcode/sr.caffemodel";
        void detect(string location)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();

            using var wechatQrcode = OpenCvSharp.WeChatQRCode.Create(
                _wechat_QCODE_detector_prototxt_path, _wechat_QCODE_detector_caffe_model_path,
                                                        _wechat_QCODE_super_resolution_prototxt_path, _wechat_QCODE_super_resolution_caffe_model_path);
            //using var wechatQrcode2 =new OpenCvSharp.QRCodeDetector();

            using var src = Cv2.ImRead(location);
            var markerMask = new Mat();
            Cv2.Threshold(src,markerMask,100,255, ThresholdTypes.Binary);
            //   var result= wechatQrcode2.DetectAndDecode(src, out Point2f[] points);
            //    var ttt = points.Length;
            sw.Stop();
            StringBuilder sb = new StringBuilder();
            wechatQrcode.DetectAndDecode(markerMask, out var rects, out var texts);
            sb.Append("耗时" + sw.ElapsedMilliseconds.ToString() + "ms\r\n");
            for (int i = 0; i < rects.Length; i++)
            {
                var x1 = rects[i].At<float>(0, 0);
                var y1 = rects[i].At<float>(0, 1);
                var x2 = rects[i].At<float>(2, 0);
                var y2 = rects[i].At<float>(2, 1);
                var result = texts[i];
                sb.Append("内容：" + result + " 位置：" + x1 + "， " + y1 + "， " + x2 + "， " + y2 + "\r\n");
            }
            MessageBox.Show(sb.ToString());
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                detect(openFileDialog.FileName);
            }
        }
    }
}
